package pokerserver.core.network;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import pokerserver.core.ServerModel;
import common.Message;

/**
 * A thread running on the server, one for each client connected and which can
 * recieve messages from the server, and stuff.
 * 
 * @author Aron
 * 
 */
public class ServerThread extends Thread {

	/**
	 * Class variables
	 */
	private Socket socket;
	private Message msgObject;
	private ObjectInputStream in;
	private ObjectOutputStream out;

	public ServerThread(Socket socket) {
		super("ServerThread");
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			// Create output- and input streams.
			out = new ObjectOutputStream(socket.getOutputStream());
			in = new ObjectInputStream(socket.getInputStream());

			// "Endless" while-loop.
			while ((msgObject = (Message) in.readObject()) != null) {
				// Process the message.
				Message output = ServerProtocol.processMessage(this, msgObject);
				// WRITE the message back
				out.writeObject(output);
				out.flush();
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			ServerModel.getInstance().removePlayer(this);
			try {
				// Kill this thread. We don't need it any more.
				this.join();
			} catch (InterruptedException e1) {
				// We shouldn't really end up here, ever.
				System.out.println("I just don't know anymore");
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}

	public Socket getSocket() {
		return socket;
	}

}
